<template>
    <div>
        <div>
            <input type="file" @change="onFileChanged">
        </div>
        <div class="row center" style="margin-top:30px">
            <video ref="refVideo" v-show="mediaType=='video'" controls autoplay :style="{'max-width':stageWidth+'px', 'max-height':stageHeight+'px'}"></video>
            <audio ref="refAudio" v-show="mediaType=='audio'" controls autoplay></audio>
            <img ref="refImg" v-show="mediaType=='image'" :style="{'max-width':stageWidth+'px', 'max-height':stageHeight+'px'}">
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, Ref, reactive, onMounted } from 'vue'
import { FrameBuffer } from './FrameBuffer';
import { CaptureMedia } from './Capture';


const frameBuffer = inject<FrameBuffer>("frameBuffer") as FrameBuffer

const capture = reactive(new CaptureMedia('media', frameBuffer))

const mediaType = ref('')
let mediaEle: any = null
// const bMeidaFileValid = ref<any>(false)

const refVideo = ref(null) as unknown as Ref<HTMLVideoElement>
const refAudio = ref(null) as unknown as Ref<HTMLVideoElement>
const refImg = ref(null) as unknown as Ref<HTMLImageElement>

const stageWidth = inject("stageWidth") as Ref<number>
const stageHeight = inject("stageHeight") as Ref<number>

onMounted(()=>{
    // capture.attach(refVideo.value)
    capture.setStageSize(stageWidth.value, stageHeight.value)
})


function onFileChanged(e) {
    let mediaFile = e?.target?.files[0] || null
    if(!mediaFile) {
        return
    }
    
    let bCanPlay = refVideo.value.canPlayType(mediaFile.type)
    let type = (mediaFile.type.split('/')||[])[0]

    if(type=='video' && bCanPlay) {
        mediaEle = refVideo.value    
        refAudio.value.pause()
    }
    else if(type=='audio' && bCanPlay) {
        mediaEle = refAudio.value
        refVideo.value.pause()
    }
    else if(type=='image') {
        mediaEle = refImg.value
    }
    else {
        mediaType.value = ''
        window.$message.info("选择的不是有效的媒体文件")
        return
    }

    mediaType.value = type

    capture.attach(mediaEle)
    
    mediaEle.src = URL.createObjectURL(mediaFile)

    capture.start()
}

function getCapture() {
    return capture
}

async function onenter() {
    capture.setStageSize(stageWidth.value, stageHeight.value)
}

defineExpose({getCapture, onenter})
</script>